package com.kristin.proxy.cglib;

import com.kristin.proxy.Dog;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @ClassName CglibMethodInterceptor
 * @Description TODO
 * @Author Kristin
 * @Date 2020/09/14 15:23:14
 * @Version 1.0.0
 */
public class CglibMethodInterceptor implements MethodInterceptor {

    public Object CglibProxyGeneratory(Class target) {
        // 创建增强器
        Enhancer enhancer = new Enhancer();

        // 设置需要增强的目标类
        enhancer.setSuperclass(target);

        // 拦截方法
        enhancer.setCallback(this);

        // 创建代理类
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before");
        Object result = methodProxy.invokeSuper(o, objects);        //Object result = method.invoke(target, args);
        System.out.println("after");
        return null;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        System.out.println(System.getProperty("user.dir"));        /** 开启 保存cglib生成的动态代理类类文件*/
        Field field = System.class.getDeclaredField("props");
        field.setAccessible(true);
        Properties props = (Properties) field.get(null);
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, System.getProperty("user.dir"));//dir为保存文件路径
        props.put("net.sf.cglib.core.DebuggingClassWriter.traceEnabled", "true");
        CglibMethodInterceptor interceptor = new CglibMethodInterceptor();
        Dog dog = (Dog)interceptor.CglibProxyGeneratory(Dog.class);
        dog.call();
    }

}
